# coding=utf-8

import os
import warnings
from parse.sdb_parser import ECU, Signal

import openpyxl

from utils.payload import EncodeType, TypeEnum
from parse.csv2xlsx import delxlsx, dealFile

class TimeoutParser:

    def __init__(self) -> None:
        self.ecu: ECU = ECU("TIMEOUT", 99)

    def __loadExcle(self, path) -> openpyxl.Workbook:
        with warnings.catch_warnings(record=True):
            excle = openpyxl.load_workbook(path)
            return excle

    def parse(self,dir):
        exclePath = os.path.join(dir,"timeout.xlsx")
        dealFile(exclePath) #假如有csv_dir则替换xlsx， 兼容没有csv_dir场景
        excle = self.__loadExcle(exclePath)
        sheet = excle["Signals"]
        index = 1
        timeoutEncode =EncodeType("Timeout",None,isEnum=True)
        timeoutEncode.addMember("{name} = {value}".format(name="NoTimeout",value="0"))
        timeoutEncode.addMember("{name} = {value}".format(name="Timeout",value="1"))
        print("time out max row {}".format(str(sheet.max_row)))
        for row_index in range(2, sheet.max_row+1):
            signalName = sheet.cell(row_index, 3).value
            if signalName is None:continue
            desc = str(sheet.cell(row_index, 6).value)
            signal = Signal(str(signalName), TypeEnum.uint8_t, "",
                            "", "1", "0", "", timeoutEncode, desc, 1, index)
            self.ecu.addRxSignal(signal)
            index += 1
        delxlsx(exclePath)
